<template>
  <div class="wrap">
    <div class="d-flex align-items-center d-top">
      <label class="el-form-item__label">{{
          $t('message.FastenerInfoExportDlg.selectedInstanceNode')
        }}：</label>
      <query-list
        :tipMsg="$t('message.FastenerInfoExportDlg.assemblyInstanceNode')"
        v-model="selectedInstanceNode"
        :active="queryListActiveMap.selectedInstanceNode"
        @switchQuery="switchQuery('selectedInstanceNode')">
      </query-list>
    </div>
    <div v-if="!loaded">
      <div id="dataLoading" v-loading="!loaded" :element-loading-text="$t('message.FastenerInfoExportDlg.loading') + loadedPercent + $t('message.FastenerInfoExportDlg.loadedPercent')"
           :style="{width: '100%', height: 100 + 'px'}">
        <iframe v-show="loaded" id="dialogPluginIframe"
                :style="{width: '100%', height: 100 + 'px'}"></iframe>
      </div>
    </div>
    <!--    <div class="border fastenerAttributeMessageBox" tabindex="-1">-->
    <!--      <FastenerInfoContent :assembly-tree-fastener-attribute-info-list="assemblyTreeFastenerAttributeInfoList"-->
    <!--                                              :is-export-data="isExportData"-->
    <!--      />-->
    <!--    </div>-->
    <div class="btn">
      <el-button type="primary"
                 size="small"
                 :disabled="componentState"
                 @click="exportData">{{ $t('message.FastenerInfoExportDlg.export') }}
      </el-button>
      <el-button size="small"
                 @click="cancel">{{ $t('message.FastenerInfoExportDlg.close') }}
      </el-button>
    </div>
  </div>
</template>

<script>
import {fastenerStatisticsCommand} from "../../../command/FastenerStatisticsCommand";
import FastenerInfoContent from "./FastenerInfoContent.vue";
import DialogMixin from "../DialogMixin";
import {fastenerPartNumberMap, FastenerPartNumberType} from "./FastenerPartNumberType";
import * as XLSX from "xlsx";
import {materialSettingCommand} from "../../../command/MaterialSettingCommand";

export default {
  mixins: [DialogMixin],
  name: "FastenerInfoExportDlg",
  components: {FastenerInfoContent},
  data() {
    return {
      assemblyTree: null,//装配树
      assemblyTreeFastenerAttributeInfoList: [],//紧固件列表
      workspaceMode: '',
      componentState: false,
      loaded: true,
      loadedPercent: 0,
      fastenerInfo:[],

      queryListActiveMap: {
        selectedInstanceNode: 1,
      },
      selectedInstanceNode: [], //选中节点 显示名称
    }
  },
  methods: {
    exportData() {
      this.generateExcel();
      fastenerStatisticsCommand.closeActiveCmd();
    },



    //结构树上的信息获取紧固件相关信息
    async traverseAssemblyTree(instanceList) {
      if (instanceList === 0 || !instanceList) {
        return;
      }

      //获取所有子节点且类型为零件的信息
      let instanceNodeList = await fastenerStatisticsCommand.getAllChildrenNode(instanceList,1);

      for (let i = 0; i < instanceNodeList.length; i++) {
        let instanceName = instanceNodeList[i].name;
        //let index = instanceName.indexOf('<');
        let partNumber = instanceName.replace(/<[^>]*>/g, '');

        //通过当前节点名称直接匹配数据库中的数据
        for(let fastenerIndex = 0;fastenerIndex < this.fastenerInfo.length;fastenerIndex++){
          let fastenerInfo = this.fastenerInfo[fastenerIndex];
          if(partNumber.indexOf(fastenerInfo.partNumber) === 0){
            let fastenerIndex = this.assemblyTreeFastenerAttributeInfoList.findIndex(item => item.fastenerNumber === fastenerInfo.partNumber);
            //如果在列表中已经存在则直接添加数量，如果没有则新建一个加入
            if (fastenerIndex !== -1) {
              this.assemblyTreeFastenerAttributeInfoList[fastenerIndex].fastenerCount++;
              this.assemblyTreeFastenerAttributeInfoList[fastenerIndex].partNumber += "," + instanceName;
            }else{
              let fastenerAtt = {
                fastenerNumber: fastenerInfo.partNumber,
                fastenerCount: 1,
                weight: fastenerInfo.weight,
                partNumber: instanceName,
              }
              this.assemblyTreeFastenerAttributeInfoList.push(fastenerAtt);
            }
            break;
          }
        }

        continue;
        //通过当前参考名称获取对应数据库里的名称获取对应的数据
        await fastenerStatisticsCommand.getPartInfoByPartNumber(partNumber, res => {
          if (res.length > 0) {
            let fastenerPartNumber = res[0].fastenerPartNumber;

            let fastenerIndex = this.assemblyTreeFastenerAttributeInfoList.findIndex(item => item.fastenerNumber === fastenerPartNumber);
            if (fastenerIndex !== -1) {
              this.assemblyTreeFastenerAttributeInfoList[fastenerIndex].fastenerCount++;
              this.assemblyTreeFastenerAttributeInfoList[fastenerIndex].partNumber += "," + instanceName;
            } else {
              let weight = this.getFastenerWeightByPartNumber(fastenerPartNumber);
              if (weight && weight !== 0) {

                let fastenerAtt = {
                  fastenerNumber: fastenerPartNumber,
                  fastenerCount: 1,
                  weight: weight,
                  partNumber: instanceName,
                }
                this.assemblyTreeFastenerAttributeInfoList.push(fastenerAtt);
              }
            }
          }
        })
      }
    },

    //导出excel
    generateExcel() {
      let data = [];
      const strTitleLine = [
        "编号",
        "紧固件牌号",
        "数量",
        "单重",
        "总重",
        //"名字",
      ];
      data.push(strTitleLine);
      let no = 0;
      this.assemblyTreeFastenerAttributeInfoList.forEach(item => {
        let strLine = [];
        strLine.push(++no);
        strLine.push(item.fastenerNumber);
        strLine.push(item.fastenerCount);
        strLine.push(item.weight);
        strLine.push(item.weight * item.fastenerCount);
        //strLine.push(item.partNumber);
        data.push(strLine);
      });

      if (data?.length > 0) {
        let workBook = XLSX.utils.book_new();
        let workSheet = XLSX.utils.aoa_to_sheet(data);

        // let cellStyle = {
        //   alignment:{horizontal: "center",vertical:"center"}
        // }
        // let range = XLSX.utils.decode_range(workSheet['!ref']);
        // for(let row = 0;row < data.length;row++){
        //   for(let col = range.s.c;col <= range.e.c;col++){
        //     let cell = workSheet[XLSX.utils.encode_cell({r:row,c:col})];
        //     cell.s =cellStyle;
        //     cell.v = cell.v;
        //     cell.t = 's';
        //   }
        // }
        //设置列宽
        workSheet['!cols'] = [{wch : 5},
          {wch : 15}];

        //设置内容居中,无效？
        // workSheet['!full-cols'] = [{
        //   wch : 15,
        //   alignment:{horizontal: "center",vertical:"center"}
        // }]

        //遍历居中，也无效？
        /*Object.keys(workSheet).forEach(cell =>{
          if(cell[0] === "!"){
            return;
          }
          workSheet[cell].s = {
            alignment:{horizontal: "center",vertical:"center"}
          }
        })*/

        XLSX.utils.book_append_sheet(workBook, workSheet, "紧固件统计");
        let excelBuffer = XLSX.write(workBook, {bookType: 'xlsx', type: 'array'});
        let dataBlob = new Blob([excelBuffer], {type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8'});
        saveAs(dataBlob, '紧固件统计表.xlsx');
      } else {
        fastenerStatisticsCommand.eventBusAlertMsg("无紧固件统计数据，无法导出数据文件", "waring");
      }
    },


    //查找对应的紧固件信息
    getFastenerWeightByPartNumber(partNumber){
      let partInfo = this.fastenerInfo.find(item => item.partNumber === partNumber);
      if(partInfo && partInfo.weight){
        return partInfo.weight;
      }
    },

    changePluginContainerHeight() {
      fastenerStatisticsCommand.changePluginContainerHeight({
        minWidth: this.$el.clientWidth, maxHeight: this.$el.clientHeight
      });
    },
    cancel() {
      fastenerStatisticsCommand.closeActiveCmd();
    },
    //当前激活的选取框切换
    switchQuery(name) {
      for (const key in this.queryListActiveMap) {
        if (key === name) {
          this.queryListActiveMap[key] = 1;
        } else {
          this.queryListActiveMap[key] = 0;
        }
      }
    },
    checkSelectedNodeType(node) {
      if (node.type === 'assembly') {
        return true;
      }
      return false;
    },
    //处理拾取的实例节点
    handlePickInstance() {
      fastenerStatisticsCommand.handlePickInstance((res) => {
        let instanceItem = res?.instance;//instanceList
        this.selectedInstanceNode = [];
        if (!!instanceItem && instanceItem.length) {
          this.selectedInstanceNode = instanceItem;
        }

        fastenerStatisticsCommand.getAllFastenerWeightInfo(info => {
          this.fastenerInfo = info.data;

          this.loaded = false;
          this.loadedPercent = 0;
          this.traverseAssemblyTree(this.selectedInstanceNode);
          this.loaded = true;
        })
      })
    },
  },
  mounted() {
    fastenerStatisticsCommand.init(800, 550, 550, () => {
      this.handlePickInstance();
      this.changePluginContainerHeight();
    });
  },
}
</script>

<style scoped>
.wrap {
    font-size: 12px;
}
</style>
